package com.supergo.sso.service.impl;

import com.supergo.http.HttpResult;
import com.supergo.pojo.User;
import com.supergo.service.base.impl.BaseServiceImpl;
import com.supergo.sso.pojo.UserInfo;
import com.supergo.sso.service.UserService;
import com.supergo.sso.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public HttpResult doLogin(UserInfo userInfo) {
        //根据用户名查询用户信息
        User query = new User();
        query.setUsername(userInfo.getUsername());
        List<User> list = this.findByWhere(query);
        // 如果没有说明用户不存在, 返回失败
        if(list == null || list.size() == 0){
            return HttpResult.error(401, "用户或密码错误");
        }
        // 如果有结果，判断密码是否正确
        User user = list.get(0);
        // 如果密码不正确返回失败
        if(!BCrypt.checkpw(userInfo.getPassword(), user.getPassword())){
            return HttpResult.error(401, "用户名或密码错误");
        }
        // 如果密码正确则登录成功
        // 生成token并返回
        String token = jwtUtil.createToken(user.getId() + "", user.getUsername(), "user");
        return HttpResult.ok(token);
    }
}
